package com.mazaiting.auth.security.extension.captcha;

import com.mazaiting.auth.constant.SecurityConst;
import com.mazaiting.auth.enums.GrantTypeEnum;
import com.mazaiting.auth.security.extension.base.BaseTokenGranter;
import com.mazaiting.auth.utils.VerifyCodeUtil;
import com.mazaiting.redis.service.IRedisStringService;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 验证码授权模式授权者
 * 声明授权者 CaptchaTokenGranter 支持授权模式 captcha
 * 根据接口传值 grant_type = captcha 的值匹配到此授权者
 * 匹配逻辑详见下面的两个方法
 * @see org.springframework.security.oauth2.provider.CompositeTokenGranter#grant(String, TokenRequest)
 * @see org.springframework.security.oauth2.provider.token.AbstractTokenGranter#grant(String, TokenRequest)
 */
public class CaptchaTokenGranter extends BaseTokenGranter {

    private final IRedisStringService redisStringService;

    public CaptchaTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
                               OAuth2RequestFactory requestFactory, AuthenticationManager authenticationManager,
                               IRedisStringService redisStringService
    ) {
        super(tokenServices, clientDetailsService, requestFactory, GrantTypeEnum.CAPTCHA.getValue(), authenticationManager);
        this.redisStringService = redisStringService;
    }

    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        // 参数
        Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
        // 获取验证码
        String code = parameters.get(SecurityConst.KEY_CODE);
        // 获取 UUID
        String uuid = parameters.get(SecurityConst.KEY_UUID);
        // 获取用户名
        String username = parameters.get(SecurityConst.KEY_USER_NAME);
        // 获取密码
        String password = parameters.get(SecurityConst.KEY_PASSWORD);
        // 校验验证码
        VerifyCodeUtil.check(redisStringService, SecurityConst.VALIDATION_CODE_KEY_PREFIX + uuid, code);
        // 和密码模式一样的逻辑
        AbstractAuthenticationToken userAuth = new UsernamePasswordAuthenticationToken(username, password);
        // 移除后续无用参数
        parameters.remove(SecurityConst.KEY_PASSWORD);
        parameters.remove(SecurityConst.KEY_CODE);
        parameters.remove(SecurityConst.KEY_UUID);
        userAuth.setDetails(parameters);
        return authenticate(client, tokenRequest, userAuth);
    }
}
